import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Radio, message, Typography, Divider, Spin } from 'antd';
import { PayCircleOutlined, CreditCardOutlined, MobileOutlined } from '@ant-design/icons';
import { Order } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';

const { Title, Text } = Typography;

const Payment: React.FC = () => {
  const { orderId } = useParams<{ orderId: string }>();
  const [order, setOrder] = useState<Order | null>(null);
  const [paymentMethod, setPaymentMethod] = useState('alipay');
  const [loading, setLoading] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    if (orderId) {
      const orders = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
      const found = orders.find(o => o.id === orderId);
      setOrder(found || null);
    }
    setPageLoading(false);
  }, [orderId]);

  const paymentMethods = [
    {
      key: 'alipay',
      label: '支付宝',
      icon: <PayCircleOutlined style={{ color: '#1890ff' }} />
    },
    {
      key: 'wechat',
      label: '微信支付',
      icon: <MobileOutlined style={{ color: '#52c41a' }} />
    },
    {
      key: 'bank',
      label: '银行卡',
      icon: <CreditCardOutlined style={{ color: '#722ed1' }} />
    }
  ];

  const handlePayment = async () => {
    if (!order) return;

    setLoading(true);
    
    try {
      // 模拟支付过程
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 更新订单状态
      const orders = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
      const updatedOrders = orders.map(o => 
        o.id === order.id 
          ? { ...o, status: 'paid' as const, updatedAt: new Date().toISOString() }
          : o
      );
      Storage.set(STORAGE_KEYS.ORDERS, updatedOrders);

      message.success('支付成功！');
      navigate(`/order/${order.id}`);
    } catch (error) {
      message.error('支付失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (pageLoading) {
    return <div style={{ textAlign: 'center', padding: '50px 0' }}><Spin size="large" /></div>;
  }

  if (!order) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Text>订单不存在</Text>
        <br />
        <Button type="primary" onClick={() => navigate('/')}>返回首页</Button>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 600, margin: '0 auto' }}>
      <Title level={2}>订单支付</Title>

      {/* 订单信息 */}
      <Card title="订单信息" style={{ marginBottom: 16 }}>
        <div style={{ marginBottom: 16 }}>
          <Text strong>订单号：</Text>
          <Text>{order.id}</Text>
        </div>
        <div style={{ marginBottom: 16 }}>
          <Text strong>收货人：</Text>
          <Text>{order.address.name} {order.address.phone}</Text>
        </div>
        <div style={{ marginBottom: 16 }}>
          <Text strong>收货地址：</Text>
          <Text>
            {order.address.province} {order.address.city} {order.address.district} {order.address.detail}
          </Text>
        </div>
        <Divider />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text>共 {order.items.length} 件商品</Text>
          <Text style={{ fontSize: 18 }}>
            应付金额: <span className="price-current">¥{order.totalAmount.toFixed(2)}</span>
          </Text>
        </div>
      </Card>

      {/* 支付方式 */}
      <Card title="选择支付方式">
        <Radio.Group 
          value={paymentMethod} 
          onChange={(e) => setPaymentMethod(e.target.value)}
          style={{ width: '100%' }}
        >
          {paymentMethods.map(method => (
            <Radio 
              key={method.key} 
              value={method.key} 
              style={{ 
                width: '100%', 
                marginBottom: 16,
                padding: '12px',
                border: '1px solid #f0f0f0',
                borderRadius: 6
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {method.icon}
                <Text style={{ marginLeft: 8 }}>{method.label}</Text>
              </div>
            </Radio>
          ))}
        </Radio.Group>

        <div style={{ marginTop: 32, textAlign: 'center' }}>
          <Button size="large" onClick={() => navigate(-1)} style={{ marginRight: 16 }}>
            返回
          </Button>
          <Button 
            type="primary" 
            size="large" 
            onClick={handlePayment}
            loading={loading}
          >
            确认支付 ¥{order.totalAmount.toFixed(2)}
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default Payment;
